package web.interceptor;

import javax.servlet.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2015/1/23.
 */
public class CharFilter implements Filter{
    private String charSet;

    @Override
    public void init(FilterConfig config) throws ServletException {
        charSet = config.getInitParameter("encoding");
        if (charSet == null || charSet.length() < 1) {
            charSet = "UTF-8";
        }
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filter) {
        try {
            request.setCharacterEncoding(this.getCharSet());
            response.setCharacterEncoding(this.getCharSet());
            filter.doFilter(request, response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        this.setCharSet(null);
    }

    public void setCharSet(String charSet) {
        this.charSet = charSet;
    }

    public String getCharSet() {
        return (this.charSet);
    }
}